package com.behome.system.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.behome.common.constant.Constants;
import com.behome.common.constant.HTTPURLContants;
import com.behome.common.core.domain.AjaxResult;
import com.behome.common.utils.HTTPRequest;
import com.behome.common.utils.file.FileUtils;
import com.behome.common.utils.file.VideoUtil;
import com.behome.system.domain.TMediaSource;
import com.behome.system.mapper.TMediaSourceMapper;
import com.behome.system.service.IMediaSourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 媒资库 业务层处理
 *
 * @author behome
 */
@Service
@Slf4j
public class MediaSourceServiceImpl implements IMediaSourceService {
    @Resource
    TMediaSourceMapper mediaSourceMapper;
    @Value("${behome.mediaPath}")
    private String mediaPath;

    @Override
    public List<TMediaSource> selectMediaSourceList(TMediaSource mediaSource) {
        return mediaSourceMapper.selectMediaSourceList(mediaSource);
    }

    @Override
    public boolean checkMediaNameUnique(TMediaSource mediaSource) {
        TMediaSource mediaSourceDb = mediaSourceMapper.selectById(mediaSource.getId());
        boolean flag = false;
        if (!mediaSourceDb.getMediaName().equals(mediaSource.getMediaName())) {
            QueryWrapper<TMediaSource> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("media_name", mediaSource.getMediaName());
            flag = mediaSourceMapper.selectCount(queryWrapper) > 0;
        }
        return flag;
    }

    @Override
    public int insert(TMediaSource mediaSource) {
        return mediaSourceMapper.insert(mediaSource);
    }

    @Override
    public int update(TMediaSource mediaSource) {
        return mediaSourceMapper.updateById(mediaSource);
    }

    @Override
    public int deleteMediaTypeIds(Long[] ids) {
        List<Long> list = Arrays.asList(ids);
        List<TMediaSource> tMediaSources = mediaSourceMapper.selectBatchIds(list);
        for (TMediaSource mediaSource : tMediaSources) {
            File file = new File(mediaSource.getFilePath());
            if (file.exists()) {
                FileUtil.del(file);
            }
        }
        return mediaSourceMapper.deleteBatchIds(list);
    }

    @Override
    public AjaxResult tts(TMediaSource mediaSource) {
        try {
            HashMap<String, Object> map = new HashMap<>();
            String randomName = String.valueOf(new Date().getTime());
            String fileName = "EBDR_local_" + randomName + ".wav";
            JSONObject json = new JSONObject();
            json.putOnce("Content", mediaSource.getDetail());
            json.putOnce("FileName", fileName);
            JSONObject backJson = HTTPRequest.speechSynthesis(json, HTTPURLContants.TTL_URL);
            if (-1 != backJson.getInt("code")) {
                //这里可以获取wav格式的文件,亦可获取mp3格式的文件根据项目实际需要修改.....edit ljy
                String newFileUrl = backJson.getStr("mp3");
                String[] split = newFileUrl.split("/");
                String newFileName = split[split.length - 1];
                String localFilePath = mediaPath + File.separator + newFileName;      //保存目录
                if (!HTTPRequest.download(newFileUrl, localFilePath)) {
                    return AjaxResult.error(-1, "文转语失败");
                }
                File upgradeFile = new File(localFilePath);
                map.put("fileSize", FileUtils.readableFileSize(upgradeFile));
                map.put("timeLength", VideoUtil.getDuration(upgradeFile));
                map.put("fileName", newFileName);
                map.put("filePath", upgradeFile.getAbsolutePath());
                return AjaxResult.success("文转语成功", map);
            } else {
                return AjaxResult.error(-1, "文转语失败");
            }
        } catch (Exception e) {
            log.error("文转语失败!{}", e.getMessage());
        }
        return AjaxResult.error(-1, "文转语失败");
    }
}
